package com.fsts.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;

import javax.swing.JTextArea;

/**
 * 验证身份
 * 
 * @author
 * 
 */
public class ValedateIdentity extends Thread {
	private String receiveIp; // 接收方IP
	private int receivePort; // 接收方端口
	private JTextArea infoTextArea;
	private File file;

	public ValedateIdentity(String receiveIp, int receivePort,
			JTextArea infoTextArea, File file) {
		this.receiveIp = receiveIp;
		this.receivePort = receivePort;
		this.infoTextArea = infoTextArea;
		this.file = file;
	}

	@Override
	public void run() {
		Socket socket = null;
		DataInputStream in = null;
		DataOutputStream out = null;
		try {

			// 接收方IP地址应该从用户列表中单击某个用户名时确定，此处可以先指定Ip，比如IP=“127.0.0.1”
			// 建立一个输出流，将要发送出去的信息写到输出流中，然后刷新，以便通过网络发送出去
			// 建立一个输入流，将接收到的信息从输入流中读取出来到String 变量中，以便决定下一步的操作
			// 2)A发送“发送文件”请求给B，然后等待回复
			// A收到“同意”后，则继续下一步；否则若收到“拒绝”，则结束本次发送
			socket = new Socket(receiveIp, receivePort);
			in = new DataInputStream(socket.getInputStream());
			out = new DataOutputStream(socket.getOutputStream());
			out.writeUTF("sendFileRequest");
			out.flush();
			String response = in.readUTF();
			if ("0".equals(response.toString())) {
				infoTextArea.append("对方已经同意接收\n");
			} else if ("1".equals(response.toString())) {
				infoTextArea.append("对方拒绝接收\n");
				System.exit(0);
			}
			// 对方同意接受后，继续发送文件
			SendFile sf = new SendFile();
			sf.sendFile(receiveIp, receivePort, file.getAbsolutePath(), infoTextArea);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
